<template>
  <div>
    <el-form ref="deptForm" :model="form" label-width="120px" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option v-for="item in employees" :key="item.id" :value="item.username" :label="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit('deptForm')">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getEmployeeSimple, addDepartments } from '@/api/employees'
import { getDepartDetail, updateDepartments } from '@/api/departments'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    oldList: {
      type: Array,
      required: true
    }
  },
  data() {
    const validCode = (to, value, callback) => {
      const arr = this.isEdit ? this.oldList.filter(item => item.code !== value).map(item => item.code) : this.oldList.map(item => item.code)
      arr.includes(value) ? callback('code编码重复了') : callback
    }

    const validName = (to, value, callback) => {
      let arr = []
      if (!this.isEdit) {
        // 将平铺数组过滤里面 pid等于当前id的 的元素
        arr = this.oldList.filter(item => item.pid === this.id).map(item => item.name)
      } else {
        const obj = this.oldList.find(item => item.id === this.id)
        arr = this.oldList.filter(item => item.pid === obj.pid && item.name !== obj.name).map(item => item.name)
      }
      arr.includes(value) ? callback(value + '已经存在') : callback
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      employees: [],
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.loadEmployee()
    this.loadDetail()
  },
  methods: {
    async loadEmployee() {
      const rs = await getEmployeeSimple()
      console.log('员工信息', rs)
      this.employees = rs.data
    },
    // 执行具体的添加动作
    async doAdd() {
      // 去获取pid： 当前要添加的部门所在的父级的id
      // 从props中获取
      // 1. 组装参数
      const params = { ...this.form, pid: this.id }
      console.log(params)
      // 2. 调用接口
      const rs = await addDepartments(params)
      console.log(rs)
      // 3. 通知父组件：关闭弹层，再次更新数据
      this.$emit('success')
      // 清空内容
      this.form = {}
    },
    // 获取当前部门的详情
    async loadDetail() {
      if (this.isEdit) {
        // alert('现在是编辑，要去获取详情')
        const res = await getDepartDetail(this.id)
        console.log('现在是编辑，要去获取详情', res)
        this.form = res.data
      }
    },
    async doEdit() {
      try {
        await updateDepartments(this.form)
        this.$message({ type: 'success', message: '修改成功' })
        this.$emit('success')
      } catch (err) {
        console.log(err)
        this.$message({ type: 'error', message: err })
      }
    },
    hSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!')
          this.isEdit ? this.doEdit() : this.doAdd()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    hCancel() {
      this.$emit('success')
      this.form = {}
    },
    resetForm() {
      this.$refs.deptForm.resetFields()
      console.log('resetForm')
    }
  }
}
</script>
<style scoped>

</style>
